#!/bin/bash
# Copyright (c) 2018 Presto Labs Pte. Ltd.
# Author: jaewon

# Add this to crontab as the below
# 20 0 * * * source /home/ec2-user/.bashrc; /home/ec2-user/ops/bitmex_unavailability/python/script/bitmex_unavailability/run.sh

RECIPIENT="jaewon@prestolabs.io"

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" >/dev/null && pwd)"
cd "${SCRIPT_DIR}"

export TZ="UTC"
YESTERDAY="$(date '+%Y%m%d' -d '1 day ago')"

LOGFILE="/tmp/bitmex_unavailability_log"
MSGFILE="/tmp/bitmex_unavailability_msg"

# Run update and push to github
./update_and_pr.sh &> "${LOGFILE}"

grep 'https://' "${LOGFILE}" > "${MSGFILE}"
printf -- "----\n\n\n\n" >> "${MSGFILE}"
cat "${LOGFILE}" >> "${MSGFILE}"

# Send mail
GIT_ROOT="$(git rev-parse --show-toplevel)"
cd "${GIT_ROOT}/python"
./pyrunner coin/tool/mailer.py \
    --mailfrom='bitmex_unavailability@joomo.io' \
    --mailto="${RECIPIENT}" \
    --subject="Update bitmex unavailability ${YESTERDAY}" < "${MSGFILE}"
